package com.zw.yzk.kabu.presenter;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.view.View;

import com.app.common.download.Download;
import com.app.common.download.ProgressListener;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseApplication;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.data.network.entity.CheckUpdateEntity;
import com.zw.yzk.kabu.data.network.entity.ImTokenEntity;
import com.zw.yzk.kabu.data.network.entity.UnreadMessageEntity;
import com.zw.yzk.kabu.data.network.task.CheckUpdateTask;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.network.entity.RefreshUserInfoEntity;
import com.zw.yzk.kabu.data.network.task.UpdateDownloadTask;
import com.zw.yzk.kabu.data.utils.AppUtils;
import com.zw.yzk.kabu.data.utils.FileUtils;
import com.zw.yzk.kabu.data.utils.LogUtils;
import com.zw.yzk.kabu.data.utils.SharedPrefrenceUtils;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.im.IMUtils;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.skin.LocalSkinManager;
import com.zw.yzk.kabu.view.view.MainView;
import com.zw.yzk.kabu.view.widget.UpdateDialog;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import javax.inject.Inject;
import javax.inject.Named;

import io.rong.imlib.RongIMClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zhanwei on 2017/3/4.
 */

public class MainPresenter implements Presenter {

    private UseCase refreshUserInfo;
    private UseCase getImToken;
    private UseCase getUnreadCount;
    private UseCase checkUpdateUseCase;
    private UseCase downloadUpdateUseCase;
    private MainView mainView;
    private AppCompatActivity activity;
    private UpdateDialog updateDialog;

    @Inject
    public MainPresenter(@Named("refreshUserInfoUseCase") UseCase refreshUserInfo,
                         @Named("getImTokenUseCase") UseCase getImToken,
                         @Named("getUnreadCountUseCase") UseCase getUnreadCount,
                         @Named("checkUpdateUseCase") UseCase checkUpdateUseCase,
                         @Named("downloadUpdateUseCase") UseCase downloadUpdateUseCase,
                         AppCompatActivity activity) {
        this.refreshUserInfo = refreshUserInfo;
        this.getImToken = getImToken;
        this.checkUpdateUseCase = checkUpdateUseCase;
        this.getUnreadCount = getUnreadCount;
        this.downloadUpdateUseCase = downloadUpdateUseCase;
        this.activity = activity;
    }

    public void setView(MainView mainView) {
        this.mainView = mainView;
    }

    public void refreshUserInfo() {
        refreshUserInfo.execute(new RefreshUserInfoSubscriber(activity), new Task());
    }

    public void getImToken() {
        getImToken.execute(new GetImTokenSubscriber(activity), new Task());
    }

    public void getUnreadCount() {
        getUnreadCount.execute(new GetUnreadCountSubscriber(activity), new Task());
    }

    public void checkUpdate() {
        checkUpdateUseCase.execute(new CheckUpdateSubscriber(activity), new CheckUpdateTask(AppUtils.getAppVersionCode(activity)));
    }

    private void download(String url, File downloadDir) {
        downloadUpdateUseCase.execute(new DownloadUpdateSubscriber(activity), new UpdateDownloadTask(url, downloadDir));
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        refreshUserInfo.unSubscribe();
        getImToken.unSubscribe();
        getUnreadCount.unSubscribe();
        checkUpdateUseCase.unSubscribe();
        downloadUpdateUseCase.unSubscribe();
    }

    private Download downloader;

    private class DownloadUpdateSubscriber extends BaseSubscriber<Download> {

        public DownloadUpdateSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(final Download download) {
            super.onNext(download);
            downloader = download;
            download.setProgressListener(new ProgressListener() {
                @Override
                public void onProgress(Download download, long bytesRead, long totalBytesRead, long contentLength) {
                    LogUtils.e("zhanwei", "bytesRead: " + bytesRead);
                    int progress = (int) (totalBytesRead * 100 / contentLength);
                    updateDialog.updateProgress(progress);

                    if (progress >= 100) {
                        if (updateDialog != null && updateDialog.isShowing()) {
                            sentNotification(downloader.file().getAbsolutePath());
                            installApk(downloader.file().getAbsolutePath());
                            updateDialog.dismiss();
                        }
                        downloader.cancel();
                    }
                }
            });
            download.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.download_success));
                        LogUtils.e("zhanwei", "file: " + downloader.file().getAbsolutePath());
                    } else {
                        if (updateDialog != null) {
                            updateDialog.dismiss();
                        }
                        ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.download_error));
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if (updateDialog != null) {
                        updateDialog.dismiss();
                    }
                    ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.download_error));
                }
            });
        }

        @Override
        public String addErrorMessage() {
            if (updateDialog != null) {
                updateDialog.dismiss();
            }
            return activity.getResources().getString(R.string.download_error);
        }
    }

    private class CheckUpdateSubscriber extends BaseSubscriber<CheckUpdateEntity> {

        public CheckUpdateSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(final CheckUpdateEntity checkUpdateEntity) {
            super.onNext(checkUpdateEntity);
            if (checkUpdateEntity.result.needUpdate == 0) {
                return;
            }
            updateDialog = new UpdateDialog(activity, 1, checkUpdateEntity.result.forceUpdate == 1);
            updateDialog.setContent(checkUpdateEntity.result.updateContent);
            updateDialog.setStartListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    File dir = new File(FileUtils.getFileDownloadDir(activity) + File.separator + "kabu.apk");
                    if (!dir.getParentFile().exists()) {
                        dir.getParentFile().mkdirs();
                    }
                    download(checkUpdateEntity.result.downloadUrl, dir);
                }
            });
            updateDialog.show();
            LogUtils.e("zhanwei", "checkUpdateEntity: " + checkUpdateEntity.result.downloadUrl);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public String addErrorMessage() {
            return null;
        }
    }

    private class GetUnreadCountSubscriber extends BaseSubscriber<UnreadMessageEntity> {

        public GetUnreadCountSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(UnreadMessageEntity entity) {
            mainView.getUnreadCountSuccess(entity.result.praiseCount + entity.result.commentCount + entity.result.replyCount > 0);
        }

        @Override
        public String addErrorMessage() {
            return "";
        }
    }

    private class RefreshUserInfoSubscriber extends BaseSubscriber<RefreshUserInfoEntity> {

        public RefreshUserInfoSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(RefreshUserInfoEntity entity) {
            mainView.refreshUserInfoSuccess();
        }

        @Override
        public String addErrorMessage() {
            return "";
        }
    }

    private class GetImTokenSubscriber extends BaseSubscriber<ImTokenEntity> {

        public GetImTokenSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onNext(final ImTokenEntity entity) {
            //连接IM服务器
            IMUtils.connect(SharedPrefrenceUtils.getString(activity, SharedPrefrenceUtils.getImToken()), new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    LogUtils.e("zhanwei", "onTokenIncorrect after refresh token: " + entity.result.imToken);
                }

                @Override
                public void onSuccess(String s) {
                    //存储IM token
                    SharedPrefrenceUtils.setValue(activity, SharedPrefrenceUtils.getImToken(), entity.result.imToken);
                    LogUtils.e("zhanwei", "connect im: " + s);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    LogUtils.e("zhanwei", "connect im error : " + errorCode);
                }
            });
        }

        @Override
        public String addErrorMessage() {
            return "";
        }
    }

    //安装apk
    private void installApk(String filePath) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }

    private void sentNotification(String filePath) {
        //点击通知栏调用系统安装程序安装apk
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");

        NotificationManager nm = (NotificationManager) activity.getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat
                .Builder(BaseApplication.getInstance())
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(activity.getResources().getString(R.string.download_success))
                .setContentText(activity.getResources().getString(R.string.click_to_install))
                .build();
        nm.notify(0, notification);
    }
}
